package guowei.guligateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 *
 * 为spring容器创建CorsWebFilter组件，使浏览器能够接受跨域请求
 *TODO 网关里配置跨域。只需要在配置类中将CorsWebFilter组件注册到ioc容器里。
 */
@Configuration
public class GuliCorsFilter {

    @Bean
    public CorsWebFilter corsWebFilter(){

//          创建CorsConfigurationSource接口的实现类UrlBasedCorsConfigurationSource
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();

//          配置跨域
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);


//          注册跨域的配置   任意路径进行跨域配置
        corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsWebFilter(corsConfigurationSource);
    }
}